package top.csy8888.likework.common.confirm;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author CSY
 * @date 2025 - 10 - 15
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class ConfirmCallbackContext {
    /**
     * 注入rabbitTemplate
     */
    private final RabbitTemplate rabbitTemplate;
    /**
     * 注入所有ConfirmCallbackService的实现类
     * 在不同的业务场景调用不同的实现来处理投递失败的业务逻辑
     */
    private final Map<String,ConfirmCallbackService> confirmCallbackServiceMap;

    /**
     * 统一调用回调处理
     * 在容器初始化时就执行这个方法
     */
    @PostConstruct
    public void confirmCallback(){
        rabbitTemplate.setConfirmCallback((cdata,ack,cause) -> {
            ReturnedMessage returnedMessage = cdata.getReturned();
            if (ack){
                log.info("The message was delivered to the {}",returnedMessage.getMessage());
            }else {
                //获取回调业务实现的bean的Id
                String beanName = returnedMessage.getReplyText();
                //根据bean的名称从map中获取相应的实现类（策略选择）（使用了策略模式）
                ConfirmCallbackService confirmCallbackService = confirmCallbackServiceMap.get(beanName);
                //执行调用
                confirmCallbackService.confirmCallback(returnedMessage.getMessage());
            }
        });
    }
}
